package cn.itcast.wushangxiantu.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.itcast.wushangxiantu.BaseAdapter.GuoJiaXinXiAdapter;
import cn.itcast.wushangxiantu.BaseAdapter.GuoZhanViewPagerAdapter;
import cn.itcast.wushangxiantu.Fragment.guozhan.BianJingLiLianFragment;
import cn.itcast.wushangxiantu.Fragment.guozhan.FenZhengZhanChangFragment;
import cn.itcast.wushangxiantu.Fragment.guozhan.GuoJiaChengYuanFragment;
import cn.itcast.wushangxiantu.Fragment.guozhan.JunDuiGuanZhiFragment;
import cn.itcast.wushangxiantu.Fragment.guozhan.MeiRiJuanXianFragment;
import cn.itcast.wushangxiantu.Fragment.guozhan.RuGuoShenQinFragment;
import cn.itcast.wushangxiantu.UserData.GuoJiaXinXi;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class GuoZhanActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager viewPager;
    private TabLayout tabLayout;
    private List<Fragment> viewList = new ArrayList<>();
    private List<String> titleList = new ArrayList<>();
    private GuoZhanViewPagerAdapter adapter;
    private int gj_id;
    private TextView tvName;
    private TextView tvDJ;
    private TextView tvGJGW;
    private TextView tvGJMoeny;
    private TextView tvGJSY;
    private ListView lv;
    private TextView tvTitle;
    private GuoJiaXinXiAdapter xinXiAdapter;
    private Button btnCiSha;
    private Button btnXiuGaiGongGao;
    private Button btnTuiChu;
    public static GuoJiaXinXi guoJiaXinXi;
    private Button btnFenFa;
    private Button btnDuiHuanGongXian;

    public static GuoJiaXinXi getGuoJiaXinXi() {
        return guoJiaXinXi;
    }

    public static void setGuoJiaXinXi(GuoJiaXinXi guoJiaXinXi) {
        GuoZhanActivity.guoJiaXinXi = guoJiaXinXi;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guo_zhan);
        //注册
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        titleList.add("纷争战场");
        titleList.add("仙盟成员");
        titleList.add("弟子管制");
        titleList.add("每日捐献");
        titleList.add("入盟申请");
        titleList.add("边境历练");
        addView();
        tvName = (TextView) findViewById(R.id.tvName);
        tvDJ = (TextView) findViewById(R.id.tvDJ);
        tvGJGW = (TextView) findViewById(R.id.tvGJGW);
        tvGJMoeny = (TextView) findViewById(R.id.tvGJMoeny);
        tvGJSY = (TextView) findViewById(R.id.tvGJSY);
        lv = (ListView) findViewById(R.id.lv);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        btnCiSha = (Button) findViewById(R.id.btnCiSha);
        btnXiuGaiGongGao = (Button) findViewById(R.id.btnXiuGaiGongGao);
        btnTuiChu = (Button) findViewById(R.id.btnTuiChu);
        btnCiSha.setOnClickListener(this);
        btnXiuGaiGongGao.setOnClickListener(this);
        btnTuiChu.setOnClickListener(this);
        btnFenFa = (Button) findViewById(R.id.btnFenFa);
        btnFenFa.setOnClickListener(this);
        btnDuiHuanGongXian = (Button) findViewById(R.id.btnDuiHuanGongXian);
        btnDuiHuanGongXian.setOnClickListener(this);
    }

    private void addView() {
        Intent intent = getIntent();
        gj_id = intent.getIntExtra("gj_id", 0);
        viewList.add(new FenZhengZhanChangFragment(GuoZhanActivity.this, gj_id));
        viewList.add(new GuoJiaChengYuanFragment(GuoZhanActivity.this, gj_id));
        viewList.add(new JunDuiGuanZhiFragment(GuoZhanActivity.this, gj_id));
        viewList.add(new MeiRiJuanXianFragment(GuoZhanActivity.this, gj_id));
        viewList.add(new RuGuoShenQinFragment(GuoZhanActivity.this, gj_id));
        viewList.add(new BianJingLiLianFragment(GuoZhanActivity.this, gj_id));
        adapter = new GuoZhanViewPagerAdapter(getSupportFragmentManager(), viewList, titleList);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        getXinXi();
    }

    private void getXinXi() {
        if (gj_id == 0) {
            ToastUtil.toast(GuoZhanActivity.this, "未知错误请重新进入");
            return;
        }
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=getGuoJiaXinXi" + "&gj_id=" + gj_id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("getxinxi", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("getxinxi", res);
                GuoJiaXinXi guoJiaXinXi = new Gson().fromJson(res, GuoJiaXinXi.class);
                Message message = new Message();
                message.what = 1;
                message.obj = guoJiaXinXi;
                handler.sendMessage(message);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case 1:
                    guoJiaXinXi = (GuoJiaXinXi) message.obj;
                    if (null != guoJiaXinXi) {
                        tvName.setText("仙盟：" + guoJiaXinXi.getName());
                        tvGJMoeny.setText("仙盟金币：" + guoJiaXinXi.getGj_money());
                        tvGJSY.setText("战场收益：" + guoJiaXinXi.getGj_sy());
                        tvGJGW.setText("仙盟魔核：" + guoJiaXinXi.getGj_gw());
                        tvDJ.setText("仙盟等级：" + guoJiaXinXi.getDj());
                        tvTitle.setText(guoJiaXinXi.getTitle());
                        if (null == xinXiAdapter) {
                            xinXiAdapter = new GuoJiaXinXiAdapter(GuoZhanActivity.this);
                        }
                        xinXiAdapter.setGuoJiaXinXi(guoJiaXinXi);
                        lv.setAdapter(xinXiAdapter);
                    } else {
                        ToastUtil.toast(GuoZhanActivity.this, "服务器坏掉了");
                    }
                    break;
                case 2:
                    User user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("操作详情", user.getStw(), -1);
                        getXinXi();
                    } else {
                        ToastUtil.toast(GuoZhanActivity.this);
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        guoJiaXinXi = null;
    }

    public void GeneralDialog(String head, String content, final int num) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(GuoZhanActivity.this)
                .setTitle(head)

                .setMessage(content)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (num) {
                            case 0:
                                cisha(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                                break;
                            case 1:
                                tuich(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                                break;
                            case 2:
                                fenfa(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                                break;
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void fenfa(String usernumber, String password) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=FenFaJiangLi" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("FenFaJiangLi", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("FenFaJiangLi", res);
                Message message = new Message();
                User user = new Gson().fromJson(res, User.class);
                message.what = 2;
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    private void tuich(String usernumber, String password) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=tuich" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("tuich", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("tuich", res);
                Message message = new Message();
                User user = new Gson().fromJson(res, User.class);
                message.what = 2;
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    private void cisha(String usernumber, String password) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=cisha" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("cisha", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("cisha", res);
                Message message = new Message();
                User user = new Gson().fromJson(res, User.class);
                message.what = 2;
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    private void GeneralDialog(final String title) {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(this);
        editText.setLines(1);
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (editText.getText().toString().trim().length() > 50) {
                            ToastUtil.toast(GuoZhanActivity.this, "长度过长");
                            return;
                        }
                        setContent(editText.getText().toString().trim());
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    private void GeneralDialogNumber(final String title) {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(this);
        editText.setLines(1);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (editText.getText().toString().trim().length() > 10) {
                            ToastUtil.toast(GuoZhanActivity.this, "长度过长");
                            return;
                        }
                        duihuan(Login.getUser().getUsernumber(),Login.getUser().getPassword(),Integer.parseInt(editText.getText().toString().trim()));
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void duihuan(String usernumber, String password, int parseInt) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=GuoZhanduihuan" + "&passWord=" + Login.getUser().getPassword() + "&userNumber=" + Login.getUser().getUsernumber() + "&num=" + parseInt, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("GuoZhanduihuan", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("GuoZhanduihuan", res);
                Message message = new Message();
                User user = new Gson().fromJson(res, User.class);
                message.what = 2;
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    private void setContent(String trim) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=setContent" + "&passWord=" + Login.getUser().getPassword() + "&userNumber=" + Login.getUser().getUsernumber() + "&content=" + trim, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("setShouYi", e.getMessage());
                } catch (Exception e1) {

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.v("setContent", res);
                Message message = new Message();
                User user = new Gson().fromJson(res, User.class);
                message.what = 2;
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnXiuGaiGongGao:
                GeneralDialog("修改仙盟公告（1-50字）");
                break;
            case R.id.btnCiSha:
                GeneralDialog("刺杀盟主", "需要花费" + (guoJiaXinXi.getDj() * 1000) + "金币收买护卫弟子", 0);
                break;
            case R.id.btnTuiChu:
                GeneralDialog("退出仙盟", "退出仙盟后职位和贡献都为0哦", 1);
                break;
            case R.id.btnFenFa:
                GeneralDialog("分发奖励", "确定要抽取百分之三十的战场收益\n按照50/1的比例兑换成金币分发给贡献最高的成员嘛？\n如若战场收益大于"+(8*guoJiaXinXi.getDj()*guoJiaXinXi.getDj()*(350-5*guoJiaXinXi.getDj()))+"，仙盟等级大于十级并且" +
                        "当前成员贡献大于"+(18*guoJiaXinXi.getDj()*(50+5*guoJiaXinXi.getDj()))+"奖励变更为石魂"+(guoJiaXinXi.getDj()/5*2)+"\n每日可分发三次奖励",2 );
                break;
            case R.id.btnDuiHuanGongXian:
                GeneralDialogNumber("贡献兑换成金币比例为20/1");
                break;
        }
    }

    /**
     * 接收后处理
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shuaxing(MessageEvent messageEvent) {
        if (messageEvent.getMessage() == "getGuoJiaXinxi") {
            getXinXi();
        }
    }
}